<?php

namespace app\admin\controller\user;

use addons\jiezicommon\service\Tools;
use app\common\controller\Backend;
use app\common\library\Auth;

/**
 * 管理员管理
 *
 * @icon fa fa-user
 */
class Admin extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->whereIn('group_id', ['4'])
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $this->modelValidate = true;
        $this->view->assign('groupName', \app\admin\model\UserGroup::where('id', config('admin_group_id'))->value('name'));
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign('groupName', \app\admin\model\UserGroup::where('id', $row['group_id'])->value('name'));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }



    public function erweima($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
//        $hashids_obj = new \Hashids\Hashids(config('hashid_key'));
//        $en_code = $hashids_obj->encode($row->id, config('hashid_key'));
//        $en_code = \addons\jiezicommon\service\Tools::gen_code($ids);
        $en_code = $ids;
//        $en_code = "dafadsf";
//        $as = strToNum($en_code);
//        var_dump($en_code);die;
        /*
        $spread_url = request()->domain() . '/c/' . $en_code;
        $result = \Endroid\QrCode\Builder\Builder::create()
            ->data($spread_url)
            ->size(300)
            ->margin(10)
//                ->labelText('This is the label')
//            ->labelFont(new NotoSans(20))
//            ->labelAlignment(new LabelAlignmentCenter())
            ->build();
//            $result->saveToFile('./uploads/shop_erweims/123.png');
        */
        $config = Tools::getInstance()->getMiniProgram();
        $app = \EasyWeChat\Factory::miniProgram($config);
        $scene = $arr['query'] ?? '';
        $page = $arr['path'] ?? '';
        $page = 'pages/login/reg';
        $mode = input('mode', 0);
        $width = input('width/d', 200);

        $scene = 'code=' . $en_code;
//            var_dump($scene);die;
        $response = $app->app_code->getUnlimit($scene, [
            'page' => $page,
            'check_path' => false,
            'width' => $width,
//                'env_version' => 'develop',
//                'env_version' => 'trial',
        ]);

        if (is_array($response)) {
            $this->error($response['errmsg']);
            die;
        }
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $response->getBody()->rewind();
//            $filename = $response->save('.' . $image, $filename);
            ob_start();
            // 输出图像
            $res = imagecreatefromstring($response->getBodyContents());
            imagepng($res);
            $content = ob_get_clean();
            imagedestroy($res);
            $row['erweima'] = 'data:image/png;base64,'. base64_encode($content);
//                $result = ['image' => base64_encode($content)];
//                return json($result);
//                return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');
        }
//        $row['spread_url'] = $spread_url;
//        $row['erweima'] = $result->getDataUri();
        $row['code'] = $en_code;
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    public function check_username(){
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if(empty($params['username'])){
            $this->error('账号不能为空');
        }
        if(\think\Validate::regex($params['username'], "^\d+$")){
            $this->error('昵称不能为纯数字');
        }
        if (\app\common\model\User::getByUsername($params['username'])) {
            $this->error(__('账号已经存在'));
            return false;
        }
//        var_dump($params['username']);
        $this->success();
    }
}
